package linkedlist;

import queue.Queue;

import java.util.Objects;

/**
 * @author lynn
 * @date 18-12-14 下午6:55
 */
public class LinkListQueue<E> implements Queue<E> {

    /**
     * inner class node
     */
    private class Node {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private Node head, tail;
    private int size;

    public LinkListQueue() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    /**
     * get queue size
     *
     * @return
     */
    @Override
    public int getSize() {
        return this.size;
    }

    /**
     * get queue is empty or not
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * put an element to the queue
     *
     * @param e
     */
    @Override
    public void enqueue(E e) {

        if (Objects.isNull(tail)) {
            this.tail = new Node(e);
            this.head = this.tail;
        } else {
            this.tail.next = new Node(e);
            this.tail = this.tail.next;
        }

        size++;

    }

    /**
     * delete an element from the queue
     *
     * @return
     */
    @Override
    public E dequeue() {

        if (this.isEmpty()) {
            throw new IllegalArgumentException(" Cannot dequeue from an empty queue. ");
        }

        Node retNode = this.head;

        this.head = this.head.next;
        retNode.next = null;

        if (Objects.isNull(this.head)) {
            this.tail = null;
        }

        size--;

        return retNode.e;
    }

    /**
     * get an element from the queue
     *
     * @return
     */
    @Override
    public E getFront() {

        if (this.isEmpty()) {
            throw new IllegalArgumentException(" Queue is empty. ");
        }

        return this.head.e;
    }

    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();

        res.append("Queue: Front ");

        Node cur = this.head;
        while (Objects.nonNull(cur)) {
            res.append(cur).append("->");
            cur = cur.next;
        }

        res.append("NULL tail");
        return res.toString();
    }

    public static void main(String[] args) {


    }

}
